#include "apue.h"
#include <sys/select.h>
#define FDARR_MAX 2

int main(int argc, char **argv) {
    int fd1[2], fd2[2], fdarr[FDARR_MAX], retval, maxfdp1, n, i;
    pid_t pid; 
    fd_set readset;
    struct timeval tv;
    char line[MAXLINE];

    if (pipe(fd1) < 0 || pipe(fd2) < 0)
        err_sys("pipe error");
    if ((pid= fork()) < 0)
        err_sys("fork error");
    else if (pid > 0) { // parent
        close(fd1[1]); 
        close(fd2[1]);

        fdarr[0]= fd1[0];
        fdarr[1]= fd2[0];
        n= FDARR_MAX;
        maxfdp1= (fd1[0] > fd2[0] ? fd1[0] : fd2[0]) + 1;

        tv.tv_sec= 90;
        tv.tv_usec= 0;
        while (1) {
            if (n <= 0)
                break;

            // 因为 select 会更新 readset，这里一定记得重置
            FD_ZERO(&readset);
            FD_SET(fd1[0], &readset);
            FD_SET(fd2[0], &readset);
            if ((retval= select(maxfdp1, &readset, NULL, NULL, &tv)) > 0) {
                // read handle
                for (i=0; i<FDARR_MAX; ++i) {
                    if (fdarr[i] < 0)
                        continue;
                    if (FD_ISSET(fdarr[i], &readset) == 0)
                        continue;
                    switch (read(fdarr[i], line, MAXLINE)) {
                        case -1:
                            err_sys("read error");
                            break;
                        case 0:
                            printf("pipe %d close\n", i);
                            n--;
                            fdarr[i]= -1;
                            break;
                        default:
                            printf("fd %d read: %s\n", i, line);
                    } 
                            
                }
            }

        }

    } else {
        close(fd1[0]); 
        close(fd2[0]);
        int j;

        i= 5, j= 2;

        while (i > 0 || j > 0) {
            sleep(1);
            sprintf(line, "hello %d", i);
            n= strlen(line);
            if (write(fd1[1], line, n) != n)
                err_sys("write error");

            if (j > 0) {
                sleep(1);
                sprintf(line, "world %d", j);
                n= strlen(line);
                if (write(fd2[1], line, n) != n)
                    err_sys("write error");

            } else if (j == 0) {
                close(fd2[1]);
            }

            i--;
            j--;            
        }
        exit(0);
    }

    return (0);
}
